#!/usr/bin/perl

## mkemptybom

# A helper script to create an empty bom file (to remove the payload
# from an installer)

use strict;
{
	my $exitCode = 1;
	
	my ($DstPath) = @ENV{qw(
							EMPTY_BOM_DST
							)};

	die "No destination path specified.\n" unless $DstPath;
	
	my $PaxPath = ($DstPath =~ m{(.*)\.bom$ }x)[0] or die "Bom file name must end in .bom";
	$PaxPath .= ".pax.gz";

	## Create a secure temporary folder to work in
	my $TempPath = `mktemp -d /private/tmp/installtmp.XXXXXXXX`;

	## Strip the CR and make our desired temp destination
	chomp($TempPath);
	my $bomPath = $TempPath . "/emptybom";

	 print "Making empty bom in '$bomPath' inside '$TempPath'\n";
	## print "Making empty bom in '$DstPath' and pax in '$PaxPath.gz'\n";

	## Exercise caution on the destination path: must start with slash
	## but be at least N chars in length.

	if (length($DstPath)  <  12   ) {goto done;}
	if (       $DstPath   !~ m{^/}) {goto done;}
	
	if ( -e $DstPath) {system("rm", "-f", $DstPath);}
	if ( -e $DstPath) {warn("Failed to remove '$DstPath'\n"); goto done;}
	                  {system("/bin/mkdir", $bomPath);}
	if (($?>>8) != 0) {warn("Failed make empty bom in '$DstPath'\n"); goto done;}

	chdir($bomPath);
	
	                  {system("/usr/bin/mkbom", $bomPath, $DstPath);}
	if (($?>>8) != 0) {warn("Failed make empty bom in '$DstPath'\n"); goto done;}
	if (!-e $DstPath) {warn("Failed make empty bom in '$DstPath'\n"); goto done;}

	system ("/bin/pax", "-w", "-z", "-x", "cpio", "-f", "$PaxPath", "./");
	if (($?>>8) != 0) {warn("Failed creating empty pax in '$PaxPath'\n"); goto done;}
	if (!-e $PaxPath) {warn("Failed creating empty pax in '$PaxPath'\n"); goto done;}

	$exitCode = 0;	## Success
  done:
	## Cleanup (why can't I just `rm -rf $TempPath` ?)
	if (-e $bomPath) {system("rm", "-rf", $bomPath);}
	if (-e $TempPath) {system("rmdir", $TempPath);}

	exit($exitCode);
}
